package billrestaurant.extra.upload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.springframework.web.multipart.MultipartFile;

public class FileUpload {
	 private MultipartFile file;  
	  
	 public MultipartFile getFile() {  
	  return file;  
	 }  
	  
	 public void setFile(MultipartFile file) {  
	  this.file = file;  
	 }  
	 public String move(File destPath,String name) throws Exception{
		 if(null==destPath )throw new Exception("Moving uploadedFile Exception["+this.getClass()+"]Destination path must not be null");
		 return this.move(destPath.getAbsolutePath(), name);
	 }
	  
	 public String move(String destPath) throws Exception{
		 return this.move(destPath, null);
	 }
	 public String move(String destPath,String name) throws Exception{
		 if(null==destPath )throw new Exception("Moving uploadedFile Exception["+this.getClass()+"]Destination path must not be null");
				
		  if(null==name)
		  name=genname(file.getOriginalFilename());
		  
		  try {  
		   InputStream inputStream = file.getInputStream();  
		  if(!destPath.trim().endsWith(File.separator))
			  destPath+=File.separator;
		   File newFile = new File(destPath + name);  
		   if (!newFile.exists()) {  
		    newFile.createNewFile();  
		   }  
		   FileOutputStream outputStream = new FileOutputStream(newFile);  
		   int read = 0;  
		   byte[] bytes = new byte[1024];  
		  
		   while ((read = inputStream.read(bytes)) != -1) {  
		    outputStream.write(bytes, 0, read);  
		   }  
		   return newFile.getName();
		  } catch (IOException e) {  
		   // TODO Auto-generated catch block  
		   e.printStackTrace();  
		  }  
		  return null;
	 }

	private String genname(String originalFilename) {
		// TODO Auto-generated method stub
		if(null==originalFilename||originalFilename.lastIndexOf(".")<0) return (long)(Math.random()*100000000+5000000)+"";
	 String ext=originalFilename.substring(originalFilename.lastIndexOf(".")+1);
		  return (long)(Math.random()*100000000+5000000)+"."+ext;
	}
}
